package com.jf3q.front.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jf3q.common.domain.EduChapter;
import com.jf3q.common.domain.EduVideo;
import com.jf3q.common.es.entity.CourseEntity;
import com.jf3q.common.service.EduChapterService;
import com.jf3q.common.service.EduCourseService;
import com.jf3q.common.service.EduVideoService;
import com.jf3q.common.vo.ChapterVo;
import com.jf3q.common.vo.CourseWebVo;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.front.dto.SearchCourseDto;
import com.jf3q.front.service.EduCourseWebService;
import com.jf3q.front.service.EduOrderService;
import com.jf3q.front.service.es.CourseEntityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/coursefront")
@Tag(name = "客户端课程详情")
public class CourseWebController {
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private EduCourseWebService courseWebService;
    @Autowired
    private EduVideoService videoService;
    @Autowired
    private EduCourseService courseService;
    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    EduOrderService orderService;

    @Autowired
    CourseEntityService courseEntityService;


    @GetMapping("/getFrontCourseInfo/{courseId}")
    @Operation(summary = "获取课程详情信息")
    public ResultVo getById(@PathVariable String courseId){
        CourseWebVo courseWebVo = courseWebService.selectInfoWebById(courseId);
        if (courseWebVo ==null) {
            return ResultVo.error("不存在该课程或者已被删除");
        }
        LambdaQueryWrapper<EduChapter> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduChapter::getCourseId,courseId);
        queryWrapper.orderByAsc(EduChapter::getSort);
        //增加浏览量自增1
        Long viewCount = redisTemplate.opsForHash().increment("course_" + courseId, "viewCount", 1);
        Long buyCount = redisTemplate.opsForHash().increment("course_" + courseId, "buyCount", 0);
        courseWebVo.setViewCount(viewCount);
        courseWebVo.setBuyCount(buyCount);

        List<EduChapter> list = chapterService.list(queryWrapper);
        list.stream().map(m->{
            String id = m.getId();
            LambdaQueryWrapper<EduVideo> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(EduVideo::getChapterId,id);
            queryWrapper1.orderByAsc(EduVideo::getSort);
            List<EduVideo> videos = videoService.list(queryWrapper1);
            m.setVideos(videos);
            return m;
        }).collect(Collectors.toList());
        courseWebVo.setChapterVideoList(list);
        return ResultVo.success("course",courseWebVo);
    }

    @GetMapping("/getChapterAndVideo/{courseId}")
    @Operation(summary = "根据课程id查章节和小节")
    public ResultVo getChapter(@PathVariable String courseId){
        List<ChapterVo> list = chapterService.getChapterVideoByCourseId(courseId);
        return ResultVo.success("",list);
    }



    /**
     * 客户端首页展示的热门课程
     * @return
     */
    @GetMapping("/courseIndex")
    @Operation(summary = "获取前4条课程热门信息")
    public ResultVo index(){
        List newCourses = redisTemplate.opsForList().range("newCourses", 0, 4);
        return ResultVo.success("",newCourses);
    }



    //根据关键词全文检索-高亮显示
    @GetMapping("/search")
    @Operation(summary = "根据关键词全文检索-高亮显示")
    public ResultVo searchCourses(String keyword,
                                  @RequestParam(defaultValue = "1") Integer number,
                                  @RequestParam(defaultValue = "2")Integer size) {
        Page<CourseEntity> courseEntities = courseEntityService.searchByKeyword(keyword, number, size);
        return setResultMap(size, courseEntities);
    }



    @NotNull
    private ResultVo setResultMap(@RequestParam(defaultValue = "2") Integer size, Page<CourseEntity> courseEntities) {
        Map<String, Object> map = new HashMap<>();
        map.put("items", courseEntities.getContent());
        map.put("current", courseEntities.getNumber()+1);//页码从 0 转换为 1
        map.put("pages", courseEntities.getTotalPages());
        map.put("size", size);
        map.put("total", courseEntities.getTotalElements());
        map.put("hasNext", courseEntities.hasNext());
        map.put("hasPrevious", courseEntities.hasPrevious());
        return  ResultVo.success(map);
    }




    @PostMapping("/search/subject")
    @Operation(summary = "分类查询课程")
    public ResultVo searchBySubject(@RequestBody
                                    SearchCourseDto dto,
                                    @RequestParam(defaultValue = "1") Integer number,
                                    @RequestParam(defaultValue = "2")Integer size) {
        //把分页数据获取出来，放到map集合
        Page<CourseEntity> courseEntities = courseEntityService.searchBySubject(dto, number, size);
        return setResultMap(size, courseEntities);
    }
}
